import React from 'react';
import {
  Card,
  Button,
  Row,
  Col,
  Icon,
  Tabs,
  Table,
  Radio,
  DatePicker,
  Tooltip,
  Menu,
  Dropdown,
  Input,
  Divider,
  message,
  Upload,
  Modal,
  List,
  Switch,
  notification,
  Avatar,
  Checkbox,
} from 'antd';

import { StyleSheet, css } from 'aphrodite';

import { swap } from 'react-magic';
import styles from './AddTemplateActivity.less';
import moment from 'moment/moment';
import { getValueWithLocalStorage } from '@/utils/authority';
import config from '../../../config/web.config';

const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const { MonthPicker, RangePicker } = DatePicker;
const { Meta } = Card;

const styles_animation = StyleSheet.create({
  magic: {
    animationName: swap,
    animationDuration: '1s',
  },
});

import { connect } from 'dva';

const namespace = 'activity';

const userInfo = getValueWithLocalStorage('userinfo');

import router from 'umi/router';

const mapStateToProps = state => {
  const ret = state[namespace].ret;
  const isLoading = state[namespace].isLoading;

  return {
    ret,
    isLoading,
  };
};

const mapDispatchToProps = dispatch => {
  return {
    saveActivity: (para, _owner, callback) => {
      const action = {
        type: `${namespace}/saveActivity`,
        payload: {
          ...para,
          saveActivityCallback: callback,
          owner: _owner,
        },
      };
      dispatch(action);
    },
    editActivity: (para, _owner, callback) => {
      const action = {
        type: `${namespace}/editActivity`,
        payload: {
          ...para,
          onEditActivityCallback: callback,
          owner: _owner,
        },
      };
      dispatch(action);
    },
  };
};
@connect(
  mapStateToProps,
  mapDispatchToProps
)
export default class AddTemplateActivity extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      _id: this.props.location.query.title == undefined ? '' : this.props.location.query._id,
      title:
        this.props.location.query.title == undefined
          ? '活动标题,请不要超过20个字'
          : this.props.location.query.title,
      titledesc:
        this.props.location.query.title == undefined ? '' : this.props.location.query.titledesc,
      contents:
        this.props.location.query.title == undefined ? '' : this.props.location.query.contents,
      type: this.props.location.query.title == undefined ? '0' : this.props.location.query.type,
      previewVisible: false,
      previewImage: '',
      h_picList:
        this.props.location.query.title == undefined
          ? []
          : [
              {
                uid: '1',
                name: 'hd_h.png',
                status: 'done',
                url: this.props.location.query.h_pic,
              },
            ],
      s_picList:
        this.props.location.query.title == undefined
          ? []
          : [
              {
                uid: '2',
                name: 'hd_s.png',
                status: 'done',
                url: this.props.location.query.s_pic,
              },
            ],
      items: this.props.location.query.title == undefined ? [] : this.props.location.query.items,
      tempItem: '',
      isShowAddItemModal: false,
      starttime:
        this.props.location.query.title == undefined
          ? moment().format('YYYY-MM-DD')
          : this.props.location.query.starttime,
      endtime:
        this.props.location.query.title == undefined
          ? moment().format('YYYY-MM-DD')
          : this.props.location.query.endtime,
      mask:
        this.props.location.query.title == undefined
          ? '本活动解释权由门店负责'
          : this.props.location.query.mask,
      address:
        this.props.location.query.title == undefined ? '' : this.props.location.query.address,
      tel: this.props.location.query.title == undefined ? '' : this.props.location.query.tel,
      contacter:
        this.props.location.query.title == undefined ? '' : this.props.location.query.contacter,
      weixin: this.props.location.query.title == undefined ? '' : this.props.location.query.weixin,
      isonline:
        this.props.location.query.title == undefined ? '0' : this.props.location.query.isonline,
      isNew: this.props.location.query.title == undefined ? true : false,
      _piclist: this.props.location.query.piclist == undefined ? [] : this.props.location.query.piclist.split(',')
    };
  }

  /*****************************model's callback********************************/

  saveActivityCallback = res => {
    if (res.code == 0) {
      message.error(res.msg);
    } else {
      message.success(res.msg);
      router.push('/activity/list');
    }
  };

  /**
   * 编辑保存的回调
   * @param res
   */
  onEditsaveActivityCallback = res => {
    if (res.code == 0) {
      message.error(res.msg);
    } else {
      message.success(res.msg);
      router.push('/activity/list');
    }
  };

  componentDidMount = () => {};

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  handleChange1 = ({ file, fileList, event }) => {
    if (file.status == 'done') {
      message.success('图片上传成功');
    }
    this.updateFileList(fileList);
    this.setState({ h_picList: fileList });
  };

  handleChange2 = ({ file, fileList, event }) => {
    if (file.status == 'done') {
      message.success('图片上传成功');
    }
    this.updateFileList(fileList);
    this.setState({ s_picList: fileList });
  };

  updateFileList = (fileList) => {
    try {
      fileList.forEach(file => {
        if (file.response && file.response.url) {
          file.url = config.HttpUrl+'/file/web/' + file.response.url;
        }
      })
    } catch (error) {
      
    }
  };

  beforeUpload1 = (file, fileList) => {
    const isJPG =
      file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
    if (!isJPG) {
      message.error('只能上传.jpeg,png,jpg格式的图片');
      notification.open({
        message: '上传失败',
        description: '只能上传.jpeg,png,jpg格式的图片',
      });
      setTimeout(() => {
        this.setState({ h_picList: [] });
      }, 500);
    }

    const isLt2M = file.size / 1024 < 500;
    if (!isLt2M) {
      alert('图片需要小于500k!');
      setTimeout(() => {
        this.setState({ h_picList: [] });
      }, 500);
    }
    return isLt2M;
  };

  beforeUpload2 = (file, fileList) => {
    const isJPG =
      file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
    if (!isJPG) {
      notification.open({
        message: '上传失败',
        description: '只能上传.jpeg,png,jpg格式的图片',
      });
      message.error('只能上传.jpeg,png,jpg格式的图片');
      setTimeout(() => {
        this.setState({ s_picList: [] });
      }, 500);
    }

    const isLt2M = file.size / 1024 < 500;
    if (!isLt2M) {
      alert('图片需要小于500k!');
      setTimeout(() => {
        this.setState({ s_picList: [] });
      }, 500);
    }
    return isLt2M;
  };

  render() {
    var that = this;
    const { type, _piclist } = this.state;

    const topContent = (
      <Row className={styles.row} gutter={10}>
        <Col span={3}>
          <span className={styles.tipLab}>选择活动类型</span>
        </Col>
        <Col span={10}>
          <RadioGroup
            className={styles.typeBg}
            defaultValue={that.state.type}
            onChange={e => {
              that.setState({ type: parseInt(e.target.value) }, () => {
                if (parseInt(that.state.type) == 0) {
                  message.success('当前活动类型是:普通宣传活动');
                } else if (parseInt(that.state.type) == 1) {
                  message.success('当前活动类型是:注册登记活动');
                }else if (parseInt(that.state.type) == 2) {
                  message.success('当前活动类型是:报名活动');
                }
              });
            }}
          >
            <RadioButton value="0">普通宣传活动</RadioButton>
            <RadioButton value="2">报名活动</RadioButton>
            <Tooltip placement="topLeft" title="暂未上线">
            {/*<RadioButton disabled={false} value="1">注册登记活动 on</RadioButton>*/}
            </Tooltip>
          </RadioGroup>
        </Col>
      </Row>
    );

    const NUM_TITLE = 20;
    const NUM_TITLEDESC = 30;
    const NUM_CONTENT = 140;
    const NUM_PIC = 1;
    const userInfo = getValueWithLocalStorage('userinfo');
    const { previewVisible, previewImage } = this.state;

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );

    const uploadItemsButton = (
      <div>
        <Button
          onClick={() => {
            if (this.state.items.length >= 5) {
              message.warning('超过数量限制');
              return;
            }
            that.setState({ isShowAddItemModal: true });
          }}
          className="ant-upload-text"
        >
          +添加活动细则
        </Button>
      </div>
    );

    const dateFormat = 'YYYY-MM-DD';

    return (
      /*
        <div className={css(styles_animation.magic)}>
          <div className={styles.image1}>React-Image</div>
        </div>
        */

      /*
           小标题
           标题描述
           活动范围（保养，钣金喷漆，保险，洗车）
           活动详细介绍列表
           背景图片
           活动图片
           活动截止日期
           备注
           是否失效
           汽修地址
           咨询电话
           微信
           号码
           联系人
           门店二维码
          */
      <Card title={that.state.isNew ? '发布活动' : '编辑活动'} bordered={false}>
        {topContent}

        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>活动标题</span>
          </Col>
          <Col span={10}>
            <Input
              defaultValue={that.state.title}
              onChange={e => {
                if (e.target.value.length > NUM_TITLE) {
                  message.warning('超出字数限制');
                  return;
                }
                that.setState({ title: e.target.value });
              }}
            />
          </Col>
          <Col span={3}>
            <span>
              {NUM_TITLE - that.state.title.length}/{NUM_TITLE}
            </span>
          </Col>
        </Row>
        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>活动标题描述</span>
          </Col>
          <Col span={18}>
            <TextArea
              row={2}
              defaultValue={that.state.titledesc}
              onChange={e => {
                if (e.target.value.length > NUM_TITLEDESC) {
                  message.warning('超出字数限制');
                  return;
                }
                that.setState({ titledesc: e.target.value });
              }}
            />
          </Col>
          <Col span={3}>
            <span>
              {NUM_TITLEDESC - that.state.titledesc.length}/{NUM_TITLEDESC}
            </span>
          </Col>
        </Row>
        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>活动内容</span>
          </Col>
          <Col span={18}>
            <TextArea
              row={4}
              defaultValue={that.state.contents}
              onChange={e => {
                if (e.target.value.length > NUM_CONTENT) {
                  message.warning('超出字数限制');
                  return;
                }
                that.setState({ contents: e.target.value });
              }}
            />
          </Col>
          <Col span={3}>
            <span>
              {NUM_CONTENT - that.state.contents.length}/{NUM_CONTENT}
            </span>
          </Col>
        </Row>
        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>活动图片(横屏)</span>
          </Col>
          <Col span={18}>
            <Upload
              data={{
                fileName: moment().format('YYYY-MM-DD HH:mm:ss:SSS'),
                tel: userInfo.tel,
              }}
              headers={{ tel: userInfo.tel, type: 0 }}
              action={'/web/file/picUploadWeb?' + 'tel=' + userInfo.tel}
              listType="picture-card"
              fileList={that.state.h_picList}
              beforeUpload={this.beforeUpload1}
              onPreview={this.handlePreview}
              onChange={this.handleChange1}
              className="avatar-uploader"
            >
              {that.state.h_picList.length == NUM_PIC ? null : uploadButton}
            </Upload>
            <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
              <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>
          </Col>
        </Row>
        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>活动背景图片(竖屏)</span>
          </Col>
          <Col span={18}>
            <Upload
              data={{
                fileName: moment().format('YYYY-MM-DD HH:mm:ss:SSS'),
                tel: userInfo.tel,
              }}
              headers={{ tel: userInfo.tel, type: 1 }}
              action={'/web/file/picUploadWeb?' + 'tel=' + userInfo.tel}
              listType="picture-card"
              fileList={that.state.s_picList}
              beforeUpload={this.beforeUpload2}
              onPreview={this.handlePreview}
              onChange={this.handleChange2}
            >
              {that.state.s_picList.length == NUM_PIC ? null : uploadButton}
            </Upload>
            <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
              <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>
          </Col>
        </Row>
        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>活动细则</span>
          </Col>
          <Col span={16}>
            <List
              bordered={true}
              dataSource={that.state.items}
              renderItem={item => (
                <List.Item className={styles.itemCellStyle}>
                  <span className={styles.itmeCellTextStyle}>{item}</span>
                  <Button
                    onClick={() => {
                      const index = that.state.items.indexOf(item);
                      const _arr = that.state.items.splice(index, 1);
                      that.setState({ items: that.state.items });
                    }}
                    className={styles.itemDelBtn}
                  >
                    删除
                  </Button>
                </List.Item>
              )}
            />
          </Col>
          <Col span={3}>{uploadItemsButton}</Col>
          <Col span={2}>最多5条细则</Col>
          <Modal
            title="添加活动细则"
            visible={this.state.isShowAddItemModal}
            onOk={() => {
              var _arr = that.state.items;
              var arr = _arr.concat(that.state.tempItem);
              that.setState({
                isShowAddItemModal: false,
                items: arr,
              });
            }}
            onCancel={() => {
              that.setState({ isShowAddItemModal: false });
            }}
            okText="确认"
            cancelText="取消"
          >
            <Input
              onChange={e => {
                that.setState({ tempItem: e.target.value });
              }}
              ref="newItem"
            />
          </Modal>
        </Row>

        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>开始截止日期</span>
          </Col>
          <Col span={16}>
            <RangePicker
              defaultValue={[
                moment(that.state.starttime, dateFormat),
                moment(that.state.endtime, dateFormat),
              ]}
              onOk={value => {
                console.log('onOk: ', value);
              }}
              onChange={(date, dateString) => {
                this.setState({
                  starttime: dateString[0],
                  endtime: dateString[1],
                });
              }}
            />
          </Col>
        </Row>

        {that.state.isNew ? (
          <Row className={styles.row} gutter={10}>
            <Col span={3}>
              <span className={styles.tipLab}>是否立即上线</span>
            </Col>
            <Col span={16}>
              <Switch
                className={styles.offBtnStyle}
                checkedChildren="上线"
                unCheckedChildren="下线"
                defaultChecked
                onChange={checked => {
                  that.setState({ isonline: checked });
                }}
              />
            </Col>
          </Row>
        ) : null}

        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>活动备注</span>
          </Col>
          <Col span={18}>
            <Input
              row={2}
              defaultValue={that.state.mask}
              onChange={e => {
                if (e.target.value.length > NUM_TITLE) {
                  message.warning('超出字数限制');
                  return;
                }
                that.setState({ mask: e.target.value });
              }}
            />
          </Col>
          <Col span={3}>
            <span>
              {NUM_TITLE - that.state.mask.length}/{NUM_TITLE}
            </span>
          </Col>
        </Row>

        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>活动地址</span>
          </Col>
          <Col span={18}>
            <Input
              row={2}
              defaultValue={that.state.address}
              onChange={e => {
                if (e.target.value.length > NUM_TITLEDESC) {
                  message.warning('超出字数限制');
                  return;
                }
                that.setState({ address: e.target.value });
              }}
            />
          </Col>
          <Col span={3}>
            <span>
              {NUM_TITLEDESC - that.state.address.length}/{NUM_TITLEDESC}
            </span>
          </Col>
        </Row>

        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>咨询电话</span>
          </Col>
          <Col span={5}>
            <Input
              row={2}
              defaultValue={that.state.tel}
              onChange={e => {
                that.setState({ tel: e.target.value });
              }}
            />
          </Col>
        </Row>

        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>微信号</span>
          </Col>
          <Col span={5}>
            <Input
              row={2}
              defaultValue={that.state.weixin}
              onChange={e => {
                that.setState({ weixin: e.target.value });
              }}
            />
          </Col>
        </Row>

        <Row className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>联系人</span>
          </Col>
          <Col span={5}>
            <Input
              row={5}
              defaultValue={that.state.contacter}
              onChange={e => {
                that.setState({ contacter: e.target.value });
              }}
            />
          </Col>
        </Row>
        {
         type == '2' &&  
         <Row  className={styles.row} gutter={10}>
          <Col span={3}>
            <span className={styles.tipLab}>报名活动必填项</span>
          </Col>
          <Col span={18}>
            <Checkbox.Group
              value={_piclist}
              onChange={values => {
                that.setState({ _piclist: values });
              }}
            >
              <Checkbox value="name">联系人</Checkbox>
              <Checkbox value="tel">tel</Checkbox>
            </Checkbox.Group>
          </Col>
        </Row>
        }

        <Row className={styles.row} gutter={48}>
          <Col offset={3} span={18}>
            <Button
              type="primary"
              block
              onClick={() => {
                if(this.state.type != 2) {
                  this.state.piclist = undefined
                } else {
                  this.state.piclist = this.state._piclist.join();
                }
                if (that.state.isNew) {
                  this.props.saveActivity(this.state, userInfo.tel, that.saveActivityCallback);
                } else {
                  this.props.editActivity(
                    this.state,
                    userInfo.tel,
                    that.onEditsaveActivityCallback
                  );
                }
              }}
            >
              {that.state.isNew ? '发布' : '保存编辑'}
            </Button>
          </Col>
        </Row>
      </Card>
    );
  }
}
